﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LinkClient
{
    public partial class FormMain : Form
    {
        private string dwbh = "DWI00000038";
        int number = 0;
        private int sendtime = 15;
        private bool IsAuto = true;
        MsSqlHelper mssql = new MsSqlHelper();        

        private string connection = "Data Source=127.0.0.1,1433;Initial Catalog=ksoa_pf;uid=sa;pwd=sql";

        public FormMain()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lbinfo.Text = "执行间隔：" + sendtime + "分钟 执行次数：0次";
            if (IsAuto)
            {
                if (timer1.Enabled)
                {
                    timer1.Enabled = false;
                    btnAutoSend.Text = "开始自动发送";
                }
                else
                {
                    timer1.Enabled = true;
                    timer1.Interval = 1000 * 60 * sendtime;
                    btnAutoSend.Text = "停止自动发送";
                    this.Activate();
                    this.ShowInTaskbar = true;//任务栏
                    notifyIcon1.Visible = false;
                    this.WindowState = FormWindowState.Minimized;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            number++;
            SendData();
            lbinfo.Text = "执行间隔：" + sendtime + "分钟 执行次数：" + number.ToString() + "次";
        }

        //把DataTable的某一列转化为逗号分隔字符串
        private string DataTableColumnSplit(DataTable dataTable, string strColumn)
        {
            //int[] idInts = dataTable.AsEnumerable().Select(d => d.Field<int>(strColumn)).ToArray();
            string[] idInts = dataTable.AsEnumerable().Select(d => d.Field<string>(strColumn)).ToArray();
            return String.Join(",", idInts);
        }
        public void SendData() {
            try
            {
                DataSourceSp();
                DataSourceDj();
                WriteLog("数据更新成功！", false);
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString(), true);
            }
        }

        public void DataSourceSp()
        {
            try
            {
                //DataTable newdt = new DataTable();
                DataTable spkfk_dt = new DataTable();
                string sql = "";
                sql = " select spid,spbh,sptm,spmch,zjm,beactive,yishj,is_gdsj,is_gdzk,is_tjsp,is_hysp,is_gmp,is_gsp,is_sy,is_yp,jingd,"
                    + " denglrq,gengxshj,delrq,dw,shpchd,shpgg,kemuhao,bzqfs,tongym,shengccj,pizhwh,zhucsb,jixing,shiyzh,bulfy,chuczysx,chuffl,"
                    + " yaofpd,yongfyyl,jinjzh,zhuysx,yaowchf,youxq,shangplx,yongyfl,leibie,jlgg,shlv,koul,bzqts,maolv,jx,bzgg,lastmodifytime,"
                    + " is_cmd,is_zdyh,is_jkyp,zdyh,fuzr,is_jsh,is_lc,is_zhongyao,type_bh,zdlshj,username,zhilbz,zengp,cunchtj "
                    + " from [spkfk](nolock) where beactive='是' ";//and spid not in(" + DataTableColumnSplit (tsp,"spid")+ ")";
                spkfk_dt = mssql.ExecuteDt(sql);
                //newdt = spkfk_dt.Clone();
                for (int i = 0; i < spkfk_dt.Rows.Count; i++)
                {
                    string spid = spkfk_dt.Rows[i]["spid"].ToString();
                    if (!mssql.Getbool("select spid from spkfk(nolock) where spid='" + spid + "'", connection))
                    {
                        string items = "";
                        string colName = "";
                        for (int n = 0; n < spkfk_dt.Columns.Count; n++)
                        {
                            colName += spkfk_dt.Columns[n].ColumnName.ToString().ToLower().Trim() + ",";
                            items += "'" + spkfk_dt.Rows[i][n].ToString().Trim() + "',";
                        }
                        colName = colName.LastIndexOf(",") == colName.Length - 1 ? colName.Remove(colName.Length - 1, 1) : colName;
                        items = items.LastIndexOf(",") == items.Length - 1 ? items.Remove(items.Length - 1, 1) : items;
                        string sqlstr = "insert into [spkfk](" + colName + ")values(" + items + ")";
                        if (mssql.ExecuteSql(sqlstr, connection) > 0)
                        {
                            WriteLog("商品资料：【" + spid + "】更新成功", false);
                            //newdt.ImportRow(spkfk_dt.Rows[i]);
                        }
                    }
                }
               // dGV.DataSource = newdt;
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString(), true);
            }
        }
        public void DataSourceDj()
        {
            try
            {
                //DataTable newdt = new DataTable();
                string sql = " select djbh from [pf_ckhz](nolock) where rq>=convert(varchar(10),getdate()-180,120) and dwbh='"+dwbh+"'";
                //string sql = " select djbh from [pf_ckhz](nolock) where rq>=convert(varchar(10),getdate()-180,120) ";
                DataTable tsp = mssql.ExecuteDt(sql);
                //newdt = tsp.Clone();
                string djbhs = "";
                for (int i = 0; i < tsp.Rows.Count; i++)
                {
                    string djbh = tsp.Rows[i]["djbh"].ToString();
                    if (!mssql.Getbool("select djbh from [js_djhz](nolock) where djbh='" + djbh + "'", connection))
                    {
                        djbhs += "'" + tsp.Rows[i]["djbh"].ToString().Trim() + "',";
                        //newdt.ImportRow(tsp.Rows[i]);
                    }
                }                
                if (!string.IsNullOrEmpty(djbhs))
                {
                    djbhs = djbhs.LastIndexOf(",") == djbhs.Length - 1 ? djbhs.Remove(djbhs.Length - 1, 1) : djbhs;
                    string sqlmx = "select  djbh, dj_sn, rq, spid, dj_sort,'HWI00000001' hw, pihao, sxrq, baozhiqi, xgdjbh, recnum, duiydjbh, duiydj_cn, dw, isnull(jlgg,0) as jlgg,"
                 + " isnull(baozhshl,0) as baozhshl, lingsshl, shl, dj, hshj, koul, je, shlv, she, hsje, ml, chbdj, isnull(lshj,0) as lshj, lshje, chonghdjbh, miejph, canssl, quxsl, isjs, "
                 + " zengp, ydj, ndj, pici, yhshj, nhshj, yishj, qishjqh, is_chonghong, ch_shl, chbje, chdj_sn, yikfapsl, beizhu, yithshl, jwh, "
                 + " gebjj, rkdwbh, rkywyid, pchao, is_th, yuany, yikaifp, is_hzi, is_fuhe, yifhshl, yikfpje, Remark, is_trans, ypchao, dddjbh,"
                 + " dddj_sn, caigrq, zbz, islp, iskx, zsdj, is_dayin, is_fl, is_fl2"
                 + " from [pf_ckmx](nolock) where djbh in(" + djbhs + ")";
                    DataTable mxdt = mssql.ExecuteDt(sqlmx);
                    for (int i = 0; i < mxdt.Rows.Count; i++)
                    {
                        string items = "";
                        string colName = "";
                        for (int n = 0; n < mxdt.Columns.Count; n++)
                        {
                            colName += mxdt.Columns[n].ColumnName.ToString().ToLower().Trim() + ",";
                            items += "'" + mxdt.Rows[i][n].ToString().Trim() + "',";
                        }
                        colName = colName.LastIndexOf(",") == colName.Length - 1 ? colName.Remove(colName.Length - 1, 1) : colName;
                        items = items.LastIndexOf(",") == items.Length - 1 ? items.Remove(items.Length - 1, 1) : items;
                        string sqlin = "insert into [js_djmx](" + colName + ")values(" + items + ")";                       
                        mssql.ExecuteSql(sqlin, connection);
                    }
                    string sqlhz = "select  djbh, djbs, djlx, bendian, rq, 'DWI00000001' as dwbh, sh_dwbh, bezzs, kaiprq, ontime, piaohao, bm, username, ywy, heth, zph,"
                + " yuansph, danjlx, je, she, hsje, ml, chbje, lshe, jsfsid, sjsz, kpman, is_hh, is_fpwc, yikaifp, dj_chonghong, thfs, xtype,"
                + " xslx, is_zch, pmhjxs, yishj, zhy, zcqfps, zcqfpe, ywbmid, ywyid, is_chonghong, beizhu, kaipiaodjbh, kpdrq, fhdj, is_zd,"
                + " zd_dwbh, fuhr, bianh, shouhr, shouhrdh, shouhrdz, ejywy, sjywy, is_th, wtrid, weitr, shdjbh, ysr, ysr2, fapiaoh, xsjsfs,"
                + " webdjbh, is_fuhe, is_fuhe2, ddlx, is_hzi, Remark, is_trans, hkts, fahy, pzid, faplx, islp, is_fetch, is_dayin, is_fl, is_fl2"
                + " from [pf_ckhz](nolock) where djbh in(" + djbhs + ")";
                    DataTable hzdt = mssql.ExecuteDt(sqlhz);
                    for (int i = 0; i < hzdt.Rows.Count; i++)
                    {
                        string items = "";
                        string colName = "";
                        for (int n = 0; n < hzdt.Columns.Count; n++)
                        {
                            colName += hzdt.Columns[n].ColumnName.ToString().ToLower().Trim() + ",";
                            items += "'" + hzdt.Rows[i][n].ToString().Trim() + "',";
                        }
                        colName = colName.LastIndexOf(",") == colName.Length - 1 ? colName.Remove(colName.Length - 1, 1) : colName;
                        items = items.LastIndexOf(",") == items.Length - 1 ? items.Remove(items.Length - 1, 1) : items;
                        string sqlin = "insert into [js_djhz](" + colName + ")values(" + items + ")";                        
                        mssql.ExecuteSql(sqlin, connection);
                    }
                }
               // dGV.DataSource = newdt;
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString(), true);
            }
        }
        
    

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;//还原大小   可改成最大化
                this.Activate();
                this.ShowInTaskbar = true;//任务栏
                notifyIcon1.Visible = false;

            }
        }

        private void 打开主界面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;//还原大小   可改成最大化
                this.Activate();
                this.ShowInTaskbar = true;//任务栏
                notifyIcon1.Visible = false;

            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //Form1_SizeChanged事件，效果为最小化窗体时，在系统托盘区域显示程序图标及气球提示：
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;//任务栏
                notifyIcon1.Visible = true;
                notifyIcon1.ShowBalloonTip(3, "注意", "蓬州大药房总部数据正在接收中。。。", ToolTipIcon.Info);
            }
            else
            {
                this.ShowInTaskbar = true;//任务栏
                notifyIcon1.Visible = false;
            }
        }

        private void btnAutoSend_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled)
            {
                timer1.Enabled = false;
                btnAutoSend.Text = "开始自动发送";
            }
            else
            {
                timer1.Enabled = true;
                timer1.Interval = 1000 * 60 * sendtime;
                btnAutoSend.Text = "停止自动发送";
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {            
            SendData();
        }

        #region 日志
        public void WriteLog(string msg, bool isdebug)
        {
            string text = AppDomain.CurrentDomain.BaseDirectory;
            text = Path.Combine(text, "log");
            if (!Directory.Exists(text))
            {
                Directory.CreateDirectory(text);
            }
            if (isdebug)
            {
                text = Path.Combine(text, "debug");
                if (!Directory.Exists(text))
                {
                    Directory.CreateDirectory(text);
                }
            }
            text = Path.Combine(text, DateTime.Now.ToString("yyyyMMdd") + ".txt");
            if (!File.Exists(text))
            {
                File.CreateText(text).Close();
            }
            StreamWriter streamWriter = new StreamWriter(text, true, Encoding.UTF8);
            if (isdebug)
            {
                streamWriter.WriteLine("--------------------------------------------------------------------------------------------------------------------------------");
            }
            streamWriter.WriteLine("{0}  {1}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss"), msg);
            if (isdebug)
            {
                streamWriter.WriteLine("--------------------------------------------------------------------------------------------------------------------------------");
            }
            streamWriter.Flush();
            streamWriter.Close();
        }

        public void ClearLog()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
            if (Directory.Exists(path))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                FileInfo[] files = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories);
                FileInfo[] array = files;
                for (int i = 0; i < array.Length; i++)
                {
                    FileInfo fileInfo = array[i];
                    if (DateTime.Now.Subtract(fileInfo.CreationTime).Days > 30)
                    {
                        File.Delete(fileInfo.FullName);
                    }
                }
            }
        }
        #endregion

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon1.Visible = true;
                this.WindowState = FormWindowState.Minimized;
            }
            //Hide();
            e.Cancel = true;
        }

    }
}
